package com.snailct.bpp.commons.utils;



import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xml.sax.InputSource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * xml工具
 * @author andy
 *
 */
public abstract class XMLUtil {
	private XMLUtil(){}
	
	

	
	public static String doc2String(String filePath){
		Format format = Format.getPrettyFormat();
		format.setEncoding("UTF-8");// 设置xml文件的字符为UTF-8，解决中文问题
		XMLOutputter xmlout = new XMLOutputter(format);
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		SAXBuilder builder = new SAXBuilder();
		Document doc;
		try {
			doc = builder.build(filePath);
			xmlout.output(doc, bo);
			return bo.toString();
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}


	public static List<BlockData> readXml4String(InputStream xml){
		List<BlockData> results = new ArrayList<BlockData>();
		SAXBuilder builder = new SAXBuilder();

		org.jdom.Document doc;

		try{
			InputSource is = new InputSource(xml);
			doc = builder.build(is);
			Element rootElement = (Element) doc.getRootElement();


			List<?> items = rootElement.getChildren("item");
			BlockData blockData = null;
			for(int i=0;i<items.size();i++){
				blockData = new BlockData();
				Element tempElement = (Element) items.get(i);
				List<?> fields = tempElement.getChildren("field");
				blockData.setBlockId(tempElement.getAttributeValue("id"));
				Item item = null;
				for(int j=0;j<fields.size();j++){
					item = new Item();
					Element field = (Element) fields.get(i);
					item.setNum(field.getChild("seq").getValue());
					results.add(blockData);
				}


			}

		}catch (Exception e){
			e.printStackTrace();
		}
		return results;
	}
}
